
<div class="container mt-4">
    <!-- 模板选择区域 -->
    <div class="row mb-3">
        <div class="col-md-8">
            <select id="templateSelect" class="form-select">
                <option value="">-- 选择模板 --</option>
                {% for template in templates %}
                <option value="{{ template.id }}">{{ template.name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="col-md-4">
            <button id="newTemplateBtn" class="btn btn-primary me-2">新建模板</button>
            <button id="saveTemplateBtn" class="btn btn-success">保存模板</button>
        </div>
    </div>

    <!-- 属性编辑区域 -->
    <div class="card mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>属性编辑</span>
            <button id="addPropertyBtn" class="btn btn-sm btn-outline-primary">+ 添加属性</button>
        </div>
        <div class="card-body">
            <div id="propertyEditor" class="row g-3">
                <!-- 动态生成的属性行会放在这里 -->
            </div>
        </div>
    </div>

    <!-- JSON预览区域 -->
    <div class="card">
        <div class="card-header">JSON预览</div>
        <div class="card-body">
            <textarea id="jsonPreview" class="form-control" rows="5" readonly></textarea>
            <div id="jsonError" class="text-danger mt-2"></div>
        </div>
    </div>
</div>

<!-- 新建模板模态框 -->
<div class="modal fade" id="templateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">模板管理</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">模板名称</label>
                    <input type="text" id="templateName" class="form-control">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="confirmTemplateBtn" class="btn btn-primary">确认</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    let currentTemplateId = null;
    let properties = [];

    // 初始化属性编辑器
    function initEditor() {
        $('#propertyEditor').empty();
        properties.forEach((prop, index) => {
            addPropertyRow(prop.key, prop.value, index);
        });
        updateJsonPreview();
    }

    // 添加属性行
    function addPropertyRow(key = '', value = '', index = null) {
        const rowId = index !== null ? index : properties.length;
        const rowHtml = `
            <div class="col-md-5">
                <input type="text" class="form-control property-key"
                       value="${key}" placeholder="属性名" data-row="${rowId}">
            </div>
            <div class="col-md-5">
                <input type="text" class="form-control property-value"
                       value="${value}" placeholder="属性值" data-row="${rowId}">
            </div>
            <div class="col-md-2">
                <button class="btn btn-outline-danger remove-property" data-row="${rowId}">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        `;
        $('#propertyEditor').append(`<div class="row mb-2 property-row" data-row="${rowId}">${rowHtml}</div>`);

        if (index === null) {
            properties.push({key: key, value: value});
        }
    }

    // 更新JSON预览
    function updateJsonPreview() {
        const jsonArray = properties.map(prop => {
            return `{"${prop.key}":"${prop.value}"}`;
        });
        $('#jsonPreview').val(`[\n${jsonArray.join(",\n")}\n]`);
    }

    // 验证JSON格式
    function validateJson() {
        try {
            JSON.parse($('#jsonPreview').val());
            $('#jsonError').text('');
            return true;
        } catch (e) {
            $('#jsonError').text('JSON格式错误: ' + e.message);
            return false;
        }
    }

    // 事件监听
    $('#addPropertyBtn').click(() => addPropertyRow());

    $(document).on('click', '.remove-property', function() {
        const rowId = $(this).data('row');
        properties.splice(rowId, 1);
        initEditor();
    });

    $(document).on('change', '.property-key, .property-value', function() {
        const rowId = $(this).data('row');
        const isKey = $(this).hasClass('property-key');
        const value = $(this).val();

        if (isKey) {
            properties[rowId].key = value;
        } else {
            properties[rowId].value = value;
        }

        updateJsonPreview();
    });

    $('#templateSelect').change(function() {
        const templateId = $(this).val();
        if (!templateId) return;

        // 这里应该通过AJAX获取模板数据
        $.get(`/api/templates/${templateId}/`, function(data) {
            currentTemplateId = templateId;
            properties = JSON.parse(data.content);
            initEditor();
        }).fail(function() {
            alert('加载模板失败');
        });
    });

    $('#newTemplateBtn').click(function() {
        currentTemplateId = null;
        $('#templateName').val('');
        $('#templateModal').modal('show');
    });

    $('#saveTemplateBtn').click(function() {
        if (!validateJson()) {
            alert('请先修正JSON格式错误');
            return;
        }

        $('#templateModal').modal('show');
    });

    $('#confirmTemplateBtn').click(function() {
        const templateName = $('#templateName').val();
        if (!templateName) {
            alert('请输入模板名称');
            return;
        }

        const templateData = {
            name: templateName,
            content: $('#jsonPreview').val(),
            id: currentTemplateId
        };

        // 保存模板到服务器
        const url = currentTemplateId ? `/api/templates/${currentTemplateId}/` : '/api/templates/';
        const method = currentTemplateId ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            method: method,
            data: templateData,
            success: function(response) {
                alert('模板保存成功');
                $('#templateModal').modal('hide');
                location.reload(); // 刷新页面更新模板列表
            },
            error: function() {
                alert('保存模板失败');
            }
        });
    });

    // 初始化空编辑器
    initEditor();
});
</script>
